/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Search.java
 *
 * Created on Dec 20, 2008, 4:54:52 PM
 */

package GUI;

import Dictionary.Dictionary;
import GUI.other.fastSkladAdd;
import functions.Dogy;
import functions.Drugs;
import functions.Items;
import functions.Sklads;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import model.Item;
import model.Drug;
import model.Sklad_drugs;
import stuff.DrugPriceCellEditor;
import stuff.DrugPriceRenderer;
import stuff.FormException;

/**
 *
 * @author GiK
 */
public class Sklad extends javax.swing.JPanel implements GUI.other.fastAddInterface{
    // @Exception handler
    private MainFrame frame;
    private ArrayList<Item> drugs;
    private String drugText, distText, dateText, blankText, skladText, addNewText;
    private Item choosenItem;
    private JTextField activeField;
    private model.Sklad choosenSklad;

    /** Creates new form Search */
    public Sklad(MainFrame mainFr) {
        initComponents();
        frame = mainFr;
        addNewText = "<html><b>"+Dictionary.ADD_NEW+"</b>";
        blankText = Dictionary.DRUGS;
        drugText = Dictionary.DRUG_NAME;
        drugField.setText(drugText);
        drugField.setForeground(Color.gray);
        distText = Dictionary.DISTRIBUTOR;
        skladText = Dictionary.WAREHOUSE;
        skladField.setText(skladText);
        skladField.setForeground(Color.gray);
        distField.setText(distText);
        distField.setForeground(Color.gray);
        
        // BoxPoup setup
        boxPopup.add(boxList);
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        dateText = sdf.format(Calendar.getInstance().getTime());
        //dateField.setText(dateText);
        //dateField1.setText(dateText);
        dateField.setForeground(Color.gray);
        dateField1.setForeground(Color.gray);
        try {
            //searchButtonActionPerformed(null);
            //fillTable();
            ArrayList<String> types = Drugs.getTypes();
            types.add(0,blankText);
            types.add(1,"Другое");
            for(int i=0; i< types.size(); i++)
                if(!types.get(i).equals(""))
                  typeBox.addItem(types.get(i));

        } catch (SQLException ex) {
            frame.SQLException(ex);
        }

        KeyStroke keyStr = KeyStroke.getKeyStroke(KeyEvent.VK_F10,0);
        InputMap map = drugTable.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(keyStr, "f10");
        ActionMap actionMap = drugTable.getActionMap();
        actionMap.put("f10", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                         jButton2ActionPerformed(null);
                     }
             });

    }

    private void initSklad()
    {
        
    }

    private void fillTable()
    {
        DefaultTableModel model = (DefaultTableModel) drugTable.getModel();
        model.setRowCount(0);
        
        if(drugs != null)
        for(int i=0;i< drugs.size(); i++)
        {
            if(drugs.get(i) instanceof Drug)
            {
                Drug drug = (Drug)drugs.get(i);
            }
            else
            {
                Item drug = (Item)drugs.get(i);
            }

            model.addRow(new Object[]{drugs.get(i),
                                      drugs.get(i).getAmount(),
                                      drugs.get(i).getBuyPrice(),
                                      drugs.get(i).getSellPrice(),
                                      drugs.get(i).getDist() == null ? "Неизвестный":
                                          drugs.get(i).getDist().getName(),
                                      drugs.get(i).getInDate(),
                                      drugs.get(i).getSklad()
                                      });
        }
        drugTable.setModel(model);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        boxPopup = new javax.swing.JPopupMenu();
        boxList = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        dialog = new javax.swing.JDialog();
        withDrawWindow = new javax.swing.JDialog();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        itemNameField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        amountField = new javax.swing.JTextField();
        closeButton = new javax.swing.JButton();
        confirmButton = new javax.swing.JButton();
        drugField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        drugTable = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        dateField = new javax.swing.JFormattedTextField();
        typeBox = new javax.swing.JComboBox();
        distField = new javax.swing.JTextField();
        dateField1 = new javax.swing.JFormattedTextField();
        groupByName = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        skladField = new javax.swing.JTextField();
        withdrawButton = new javax.swing.JButton();

        boxPopup.setAutoscrolls(true);
        boxPopup.setMaximumSize(new java.awt.Dimension(190, 645555));
        boxPopup.setPreferredSize(new java.awt.Dimension(190, 120));

        boxList.setAutoscrolls(true);
        boxList.setMaximumSize(new java.awt.Dimension(290, 32767));
        boxList.setMinimumSize(new java.awt.Dimension(120, 23));

        list.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Добавить новое" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setMaximumSize(new java.awt.Dimension(190, 16));
        list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMouseClicked(evt);
            }
        });
        boxList.setViewportView(list);

        dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        dialog.setAlwaysOnTop(true);
        dialog.setResizable(false);
        dialog.setUndecorated(true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                dialogWindowClosed(evt);
            }
        });

        javax.swing.GroupLayout dialogLayout = new javax.swing.GroupLayout(dialog.getContentPane());
        dialog.getContentPane().setLayout(dialogLayout);
        dialogLayout.setHorizontalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        dialogLayout.setVerticalGroup(
            dialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("Списать со склада");

        jLabel3.setText("Предмет:");

        itemNameField.setEditable(false);
        itemNameField.setFont(new java.awt.Font("Tahoma", 0, 12));

        jLabel4.setText("На складе:");

        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        confirmButton.setText("Подтвердить");
        confirmButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout withDrawWindowLayout = new javax.swing.GroupLayout(withDrawWindow.getContentPane());
        withDrawWindow.getContentPane().setLayout(withDrawWindowLayout);
        withDrawWindowLayout.setHorizontalGroup(
            withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(withDrawWindowLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(withDrawWindowLayout.createSequentialGroup()
                        .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(amountField, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(itemNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(withDrawWindowLayout.createSequentialGroup()
                        .addComponent(closeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 202, Short.MAX_VALUE)
                        .addComponent(confirmButton)))
                .addContainerGap())
        );
        withDrawWindowLayout.setVerticalGroup(
            withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(withDrawWindowLayout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(itemNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(amountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                .addGroup(withDrawWindowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(confirmButton))
                .addContainerGap())
        );

        setMaximumSize(new java.awt.Dimension(704, 418));
        setMinimumSize(new java.awt.Dimension(704, 418));
        setPreferredSize(new java.awt.Dimension(704, 418));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                formFocusLost(evt);
            }
        });

        drugField.setFont(new java.awt.Font("Tahoma", 0, 14));
        drugField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                drugFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                drugFieldFocusLost(evt);
            }
        });
        drugField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                drugFieldKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                drugFieldKeyTyped(evt);
            }
        });

        searchButton.setFont(new java.awt.Font("Tahoma", 1, 14));
        searchButton.setText(Dictionary.SEARCH);
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        drugTable.setAutoCreateRowSorter(true);
        drugTable.setFont(drugTable.getFont().deriveFont(drugTable.getFont().getStyle() | java.awt.Font.BOLD, drugTable.getFont().getSize()+3));
        drugTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Название",
                "Количество",
                "Цена нетто",
                "Цена брутто",
                "Поставщик",
                "Дата ввоза",
                "Склад"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Double.class,
                java.lang.Double.class, java.lang.Double.class,
                java.lang.String.class, java.lang.Object.class,
                java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }

        });
        drugTable.getColumnModel().getColumn(3).setCellRenderer(
            new DrugPriceRenderer(null)
        );
        drugTable.getColumnModel().getColumn(3).setCellEditor(
            new DrugPriceCellEditor(null)
        );
        drugTable.getColumnModel().getColumn(0).setMinWidth(200);
        drugTable.getColumnModel().getColumn(1).setMinWidth(15);
        drugTable.getColumnModel().getColumn(2).setMinWidth(15);
        drugTable.getColumnModel().getColumn(6).setMinWidth(50);
        drugTable.setRowHeight(30);
        jScrollPane1.setViewportView(drugTable);

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton3.setText(Dictionary.CHANGE
        );
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton2.setText(Dictionary.ADD+"(F10)");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        dateField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd.MM.yyyy"))));
        dateField.setText("ДД.ММ.ГГГГ");
        dateField.setToolTipText("ДД.ММ.ГГГГ");
        dateField.setFont(new java.awt.Font("Tahoma", 1, 14));
        dateField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                dateFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                dateFieldFocusLost(evt);
            }
        });

        typeBox.setFont(new java.awt.Font("Tahoma", 1, 14));
        typeBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Всё" }));

        distField.setFont(new java.awt.Font("Tahoma", 0, 14));
        distField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                distFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                distFieldFocusLost(evt);
            }
        });
        distField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                distFieldKeyReleased(evt);
            }
        });

        dateField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd.MM.yyyy"))));
        dateField1.setText("ДД.ММ.ГГГГ");
        dateField1.setToolTipText("ДД.ММ.ГГГГ");
        dateField1.setFont(new java.awt.Font("Tahoma", 1, 14));
        dateField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                dateField1FocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                dateField1FocusLost(evt);
            }
        });

        groupByName.setFont(new java.awt.Font("Tahoma", 1, 12));
        groupByName.setText(Dictionary.GROUP_BY_NAME );
        groupByName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                groupByNameActionPerformed(evt);
            }
        });

        jLabel1.setText("  -");

        skladField.setFont(new java.awt.Font("Tahoma", 0, 14));
        skladField.setName("skladField"); // NOI18N
        skladField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                skladFieldMouseClicked(evt);
            }
        });
        skladField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                skladFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                skladFieldFocusLost(evt);
            }
        });
        skladField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                skladFieldKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                skladFieldKeyReleased(evt);
            }
        });

        withdrawButton.setFont(new java.awt.Font("Tahoma", 1, 14));
        withdrawButton.setText(Dictionary.DISPOSE);
        withdrawButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                withdrawButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(distField, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(skladField, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(drugField, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(typeBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dateField, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateField1, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE))
                            .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(groupByName, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                        .addComponent(withdrawButton, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(drugField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(typeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(distField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(skladField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupByName)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(withdrawButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        Items searchDrugs = new Items();

            if(typeBox.getSelectedIndex() > 2)
              searchDrugs.searchByStrictType(typeBox.getSelectedItem().toString());
            else if(typeBox.getSelectedIndex() == 1)
              searchDrugs.searchByTypeNot("muud");
            else if(typeBox.getSelectedIndex() == 2)
              searchDrugs.searchByStrictType("muud");

        //Sklad setup

        if(choosenSklad != null)
            searchDrugs.searchInSklad(choosenSklad.getId());
        
        if(!drugField.getText().equals(drugText) &&
                !drugField.getText().equals(""))
            searchDrugs.searchByName(drugField.getText());
        if(!distField.getText().equals(distText) &&
                !distField.getText().equals(""))
            searchDrugs.searchByDist(distField.getText());
        
        Date date1 = (Date)dateField.getValue();
        Date date2 = (Date)dateField1.getValue();
        if(date1 != null && date2 !=null && !dateField.getText().equals("ДД.ММ.ГГГГ") &&
                !dateField1.getText().equals("ДД.ММ.ГГГГ"))
        {
                searchDrugs.searchByDates(date1, date2);
        }
        if(groupByName.isSelected())
            searchDrugs.groupByName();
        try {
            drugs = searchDrugs.search();
            fillTable();
        } catch (SQLException ex) {
            frame.SQLException(ex);
        }
        
        
}//GEN-LAST:event_searchButtonActionPerformed

    public void refreshSearch()
    {
        int [] selRows = drugTable.getSelectedRows();
        searchButtonActionPerformed(null);
        for(int i=0; i< selRows.length; i++)
          drugTable.getSelectionModel().addSelectionInterval(selRows[i], selRows[i]);
    }
    private void drugFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_drugFieldKeyTyped

}//GEN-LAST:event_drugFieldKeyTyped

    private void drugFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_drugFieldFocusGained

        Dogy.focusGained((JTextField)evt.getSource(),drugText);
}//GEN-LAST:event_drugFieldFocusGained

    private void drugFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_drugFieldFocusLost
        Dogy.focusLost((JTextField)evt.getSource(),drugText);
    }//GEN-LAST:event_drugFieldFocusLost

    private void distFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_distFieldFocusGained
       Dogy.focusGained((JTextField)evt.getSource(),distText);
    }//GEN-LAST:event_distFieldFocusGained

    private void distFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_distFieldFocusLost
       Dogy.focusLost((JTextField)evt.getSource(),distText);
    }//GEN-LAST:event_distFieldFocusLost

    private void groupByNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupByNameActionPerformed
        searchButtonActionPerformed(null);
}//GEN-LAST:event_groupByNameActionPerformed

    private void dateFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateFieldFocusGained
        if((Date)dateField.getValue() == null || dateField.getText().equals("ДД.ММ.ГГГГ"))
        {
          dateField.setText(dateText);
          if(dateField.getFormatterFactory() == null)
          dateField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd.MM.yyyy"))));
        }

        dateField.setForeground(Color.black);
    }//GEN-LAST:event_dateFieldFocusGained

    private void dateField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateField1FocusGained
        if((Date)dateField1.getValue() == null || dateField1.getText().equals("ДД.ММ.ГГГГ"))
        {
           dateField1.setText(dateText);
           if(dateField1.getFormatterFactory() == null)
           dateField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd.MM.yyyy"))));
        }

        dateField1.setForeground(Color.black);
    }//GEN-LAST:event_dateField1FocusGained

    private void dateFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateFieldFocusLost
        if(dateField.getText().equals(""))
        {
            dateField.setText("ДД.ММ.ГГГГ");
            dateField.setForeground(Color.gray);
            dateField.setFormatterFactory(null);
        }
    }//GEN-LAST:event_dateFieldFocusLost

    private void dateField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateField1FocusLost
        if(dateField1.getText().equals(""))
        {
            dateField1.setText("ДД.ММ.ГГГГ");
            dateField1.setForeground(Color.gray);
            dateField1.setFormatterFactory(null);
        }
    }//GEN-LAST:event_dateField1FocusLost

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        AddToSklad add = new AddToSklad(frame,null,this);
        add.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        AddToSklad add = new AddToSklad(frame,(Item)drugTable.getValueAt(drugTable.getSelectedRow(), 0),this);
        add.setVisible(true);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void skladFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_skladFieldFocusGained
        Dogy.focusGained((JTextField)evt.getSource(),skladText);
    }//GEN-LAST:event_skladFieldFocusGained

    private void skladFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_skladFieldFocusLost
        boxPopup.setVisible(false);
        Dogy.focusLost((JTextField)evt.getSource(),skladText);
        if(skladBoxIsEmpty())
           choosenSklad = null;
    }//GEN-LAST:event_skladFieldFocusLost

    private void skladFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_skladFieldKeyPressed
        Dogy.listScroll(list, evt);
    }//GEN-LAST:event_skladFieldKeyPressed

    private void skladFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_skladFieldKeyReleased
        activeField = skladField;
        if( evt != null && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            boxPopup.setVisible(false);
            //skladField.nextFocus();
            if(!skladField.getText().equals("") || list.getSelectedIndex() >0)
            {
               listMouseClicked(null);
               searchButtonActionPerformed(null);
            }
            else
                showAddWindow();

        } else if(evt != null && evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            boxPopup.setVisible(false);
        }
        else if(!dialog.isVisible() && (evt == null || !evt.isActionKey()) ){
            try {
                list.ensureIndexIsVisible(0);
                ArrayList choices=null;
                choices= Sklads.getByName(skladField.getText());

                choices.add(0,addNewText);

                list.setListData(choices.toArray());

                boxPopup.setLocation(skladField.getLocationOnScreen().x,
                        skladField.getLocationOnScreen().y + skladField.getHeight());

                list.repaint();
                boxPopup.repaint();
                boxPopup.setVisible(true);
                
                
            } catch (SQLException ex) {
                frame.SQLException(ex);
            }
        }
    }//GEN-LAST:event_skladFieldKeyReleased

    private void skladFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_skladFieldMouseClicked
         activeField = skladField;
        if(skladField.getText().equals(""))
            skladFieldKeyReleased(null);
    }//GEN-LAST:event_skladFieldMouseClicked

    private void formFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusLost
        boxPopup.setVisible(false);
        dialog.setVisible(false);
    }//GEN-LAST:event_formFocusLost

    private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked
        boxPopup.setVisible(false);
        if ( list.getSelectedValue() != null &&
                (list.getSelectedValue().toString().equals(addNewText) ||
                list.getSelectedIndex() == -1)) {
            showAddWindow();
        } else {
            if(activeField != null) {

                activeField.setText(list.getSelectedValue().toString());

                if(activeField.getName().equals("skladField"))
                    choosenSklad = (model.Sklad)list.getSelectedValue();

            }
        }
    }//GEN-LAST:event_listMouseClicked

    private void dialogWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_dialogWindowClosed
        this.setEnabled(true);
        this.requestFocus();
}//GEN-LAST:event_dialogWindowClosed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        withDrawWindow.setVisible(false);
    }//GEN-LAST:event_closeButtonActionPerformed

    private void confirmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmButtonActionPerformed
        
        try
        {
          Sklad_drugs.updateDrugAmount(choosenItem.getRecId(),
                    Double.parseDouble(amountField.getText()));
          refreshSearch();
          withDrawWindow.setVisible(false);
        } catch(SQLException e)
        {
            frame.SQLException(e);
        }
    }//GEN-LAST:event_confirmButtonActionPerformed

    private void withdrawButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_withdrawButtonActionPerformed
        try
        {
          itemNameField.setText("");
          amountField.setText("");
          if(drugTable.getSelectedRow() == -1 )
            throw new FormException("Выделите предмет.");
          choosenItem = (Item)drugTable.getModel().getValueAt(drugTable.getSelectedRow(), 0);
          itemNameField.setText(choosenItem.toString());
          amountField.setText(choosenItem.getAmount()+"");
          withDrawWindow.pack();
          withDrawWindow.setVisible(true);
          Dogy.placeToCenter(withDrawWindow);
        } catch(Exception e)
        {
            frame.FormException(this, e.getMessage());
        }
}//GEN-LAST:event_withdrawButtonActionPerformed

    private void drugFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_drugFieldKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            searchButtonActionPerformed(null);
    }//GEN-LAST:event_drugFieldKeyReleased

    private void distFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_distFieldKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            searchButtonActionPerformed(null);
    }//GEN-LAST:event_distFieldKeyReleased

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        //System.out.println("Sklad Shown");
        if(drugTable.getRowCount() == 0)
            searchButtonActionPerformed(null);
    }//GEN-LAST:event_formComponentShown

   public void disposeDialog()
    {
          dialog.setVisible(false);
          //dialog.dispose();
    }
    public String getActiveFieldText() {
        return activeField.getText();
    }
    public JTextField getActiveField() {
        return activeField;
    }
    public void setActiveFieldText(Object obj) {
        activeField.setForeground(Color.black);
        activeField.setText("");
        if (obj instanceof model.Sklad ) {
            choosenSklad = (model.Sklad) obj;
        }
    }
    private void showAddWindow() {
        if (activeField != null && activeField.getName().equals("skladField")) {
            dialog.setContentPane(new fastSkladAdd(choosenSklad, this));
        }

        dialog.pack();
        dialog.setLocation(activeField.getLocationOnScreen().x,
                activeField.getLocationOnScreen().y + activeField.getHeight());
        dialog.setVisible(true);
    }
    private boolean skladBoxIsEmpty()
    {
      return skladField.getText().equals("") || skladField.getText().equals(skladText);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField amountField;
    private javax.swing.JScrollPane boxList;
    private javax.swing.JPopupMenu boxPopup;
    private javax.swing.JButton closeButton;
    private javax.swing.JButton confirmButton;
    private javax.swing.JFormattedTextField dateField;
    private javax.swing.JFormattedTextField dateField1;
    private javax.swing.JDialog dialog;
    private javax.swing.JTextField distField;
    private javax.swing.JTextField drugField;
    private javax.swing.JTable drugTable;
    private javax.swing.JCheckBox groupByName;
    private javax.swing.JTextField itemNameField;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JList list;
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField skladField;
    private javax.swing.JComboBox typeBox;
    private javax.swing.JDialog withDrawWindow;
    private javax.swing.JButton withdrawButton;
    // End of variables declaration//GEN-END:variables

}
